﻿using System;
using System.Collections.Generic;
using Mbs.Log;

namespace Mbs.Windows
{
    public interface ISmartPartService
    {
        void RegisterView<TViewInterface, TViewImp>();
        void RegisterView(Type viewInterfaceType, Type viewImpType);
        TViewInterface NewView<TViewInterface>();
    }

    public class SmartPartService : ISmartPartService
    {
        static ILog log = LoggerManager.Instance.CreateLogger(typeof(SmartPartService));
        private Dictionary<Type, Type> map;
        public SmartPartService()
        {
            map = new Dictionary<Type, Type>();
        }

        public void RegisterView<TViewInterface, TViewImp>()
        {
            RegisterView(typeof(TViewInterface), typeof(TViewImp));
        }

        public void RegisterView(Type viewInterfaceType, Type viewImpType)
        {
            Guard.ArgumentNotNull(viewInterfaceType, "viewInterfaceType");
            Guard.ArgumentNotNull(viewImpType, "viewImpType");
            map.Add(viewInterfaceType, viewImpType);
        }

        public TViewInterface NewView<TViewInterface>()
        {
            TViewInterface v = default(TViewInterface);

            Type type = null;
            if (map.TryGetValue(typeof(TViewInterface), out type))
            {
                try
                {
                    v = (TViewInterface)Activator.CreateInstance(type);
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                }
            }

            return v;
        }
    }
}
